import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(VueAxios, axios)

import { getToken,saveToken } from '@/utils/token.js'

import { Toast } from 'vant'

import router from '@/router/index.js'

const instance = axios.create({
  baseURL: 'http://toutiao.itheima.net',
  timeout: 10000
})

instance.interceptors.request.use(
  function (config) {
    if (getToken()) {
      config.headers.Authorization = `Bearer ${getToken().token}`
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

instance.interceptors.response.use(
  function (response) {
    return response
  },
  async function (error) {
    if (error.response && error.response.status == 401) {
      if (getToken()) {
          try { let res = await axios({
            url:'http://toutiao.itheima.net/v1_0/authorizations',
            method:'put',
            headers:{
                'Authorization':`Bearer ${getToken().refresh_token}`
            }
          })
          console.log(res);
          saveToken({
            token:res.data.data.token,
            refresh_token:getToken().refresh_token
        })
        return instance(error.config)
    }catch(err){
        Toast.fail('等先登录')
        router.push('/login')

    }
      } else {
        Toast.fail('等先登录')
        router.push('/login')
      }
    } else {
    }

    return Promise.reject(error)
  }
)

export default instance
